class Solution
{
public:
    int minIncrements(int n, vector<int> &cost)
    {
        function<pair<int, int>(int)> f = [&](int node) -> pair<int, int>
        {
            int left = 2 * node + 1;
            int right = 2 * node + 2;
            if (left >= n)
            {
                return {cost[node], 0};
            }
            auto [leftPathVal, leftInc] = f(left);
            auto [rightPathVal, rightInc] = f(right);
            int inc = abs(leftPathVal - rightPathVal);
            int pathVal = max(leftPathVal, rightPathVal) + cost[node];
            return {pathVal, inc + leftInc + rightInc};
        };
        return f(0).second;
    }
};